import datetime
import requests
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.core import serializers
from user.models import User, FeedBack
import json
import time


# Create your views here.
def login(request):
    if request.method == "GET":
        error_msg = request.session.get('error_message')
        result = {
            "code": 200,
            "msg": "error",
            "data": ""
        }
        return HttpResponse(json.dumps(result))

    elif request.method == "POST":
        openid = request.POST.get("open_id")
        user = User.objects.filter(open_id=openid)
        if user.exists():
            user = user.first()
            # json_t = json.dumps(user,skipkeys=True)
            json_user = {
                "id": user.id,
                "username": user.username,
                "opend_id": user.open_id,
                "uniacid": user.uniacid,
                "avatar_url": user.avatar_url,
                "nick_name": user.nick_name,
                "gender": user.gender,
                "country": user.country,
                "city": user.city,
                "phone": user.phone,
                "admin": user.admin,
                "status": user.status,
                "create_time": user.create_time,
                "create_id": user.create_id,
                "update_time": user.update_time,
                "update_id": user.update_id,
            }
            data = {
                "msg": "ok",
                "data": json.dumps(json_user, default=DateEncoder),
            }
            result = {
                "code": 200,
                "msg": "ok",
                "data": data,
            }

            return HttpResponse(json.dumps(result, default=DateEncoder))
        else:
            # 添加用户到数据库
            openid = request.POST.get("open_id")
            nick_name = request.POST.get("nick_name")
            avatar_url = request.POST.get("avatar_url")
            province = request.POST.get("province")
            gender = request.POST.get("gender")
            country = request.POST.get("country")
            city = request.POST.get("city")

            user = User()
            user.open_id = openid
            user.create_id = openid
            user.nick_name = nick_name
            user.avatar_url = avatar_url
            user.province = province
            user.gender = gender
            user.country = country
            user.city = city
            user.create_id = openid
            user.status = 1

            user.save()
            result = {
                "code": 200,
                "msg": "error",
                "data": ""
            }
            return HttpResponse(json.dumps(result))


def wechat(request):
    try:
        start = time.perf_counter()
        parmas = {
            'appid': "wxc7b1666efc97f194",
            'secret': "843db4e865f845ca2d6676bd74a61dba",
            'js_code': request.GET.get("code"),
            'grant_type': 'authorization_code'
        }

        url = 'https://api.weixin.qq.com/sns/jscode2session'

        r = requests.get(url, params=parmas)
        openid = r.json().get('openid', '')
        end = time.perf_counter()
        print("openid ----------:", openid)
        print('获取openid用时：', end - start, '秒')
    except Exception as ret:
        print(ret)
        result = {
            "code": 200,
            "msg": "error",
            "data": ret,
        }
        return HttpResponse(json.dumps(result))
    else:
        result = {
            "code": 200,
            "msg": "ok",
            "data": openid
        }
        return HttpResponse(json.dumps(result))


def feedback(request):
    try:
        if request.method == "GET":
            error_msg = request.session.get('error_message')
            data = {
                "code": 0,
                "msg": "意见反馈成功！",
                "data": "",
            }
            result = {
                "code": 200,
                "msg": error_msg,
                "data": data
            }
            return HttpResponse(json.dumps(result))

        elif request.method == "POST":
            open_id = request.POST.get("open_id")
            phone = request.POST.get("phone")
            device_model = request.POST.get("device_model")
            device_system = request.POST.get("device_system")
            app_version = request.POST.get("app_version")
            content = request.POST.get("content")

            feedback = FeedBack()
            feedback.open_id = open_id
            feedback.phone = phone
            feedback.device_model = device_model
            feedback.device_system = device_system
            feedback.app_version = app_version
            feedback.content = content
            feedback.status = 1
            feedback.create_id = open_id

            feedback.save()
            data = {
                "code": 1,
                "msg": "意见反馈成功！",
                "data": "",
            }
            result = {
                "code": 200,
                "msg": "ok",
                "data": data
            }
            return HttpResponse(json.dumps(result, default=DateEncoder))

    except Exception as ret:
        print(ret)
        data = {
            "code": 0,
            "msg": "意见反馈失败！",
            "data": "",
        }
        result = {
            "code": 200,
            "msg": "error",
            "data": ""
        }
        return HttpResponse(json.dumps(result))
    else:
        data = {
            "code": 0,
            "msg": "意见反馈失败！",
            "data": "",
        }
        result = {
            "code": 200,
            "msg": "error",
            "data": data
        }
        return HttpResponse(json.dumps(result))


def update(request):
    try:
        if request.method == "GET":
            error_msg = request.session.get('error_message')
            data = {
                "code": 0,
                "msg": "更新失败！",
                "data": "",
            }
            result = {
                "code": 200,
                "msg": "ok",
                "data": data
            }
            return HttpResponse(json.dumps(result))

        elif request.method == "POST":
            open_id = request.POST.get("open_id")
            phone = request.POST.get("phone")
            user = User.objects.filter(open_id=open_id)
            if user.exists():
                user = user.first()
                user.phone = phone
                user.save()
                data = {
                    "code": 1,
                    "msg": "绑定成功!",
                    "data": "",
                }
                result = {
                    "code": 200,
                    "msg": "ok",
                    "data": data
                }
                return HttpResponse(json.dumps(result))
            else:
                data = {
                    "code": 0,
                    "msg": "绑定失败！",
                    "data": "",
                }
                result = {
                    "code": 200,
                    "msg": "error",
                    "data": ""
                }
            return HttpResponse(json.dumps(result))
    except Exception as ret:
        print(ret)
        data = {
            "code": 0,
            "msg": "绑定失败！",
            "data": "",
        }
        result = {
            "code": 200,
            "msg": "error",
            "data": ""
        }
        return HttpResponse(json.dumps(result))
    else:
        data = {
            "code": 0,
            "msg": "绑定失败！",
            "data": "",
        }
        result = {
            "code": 200,
            "msg": "error",
            "data": data
        }
        return HttpResponse(json.dumps(result))


def getuser(request):
    if request.method == "GET":
        error_msg = request.session.get('error_message')
        result = {
            "code": 200,
            "msg": "error",
            "data": ""
        }
        return HttpResponse(json.dumps(result))

    elif request.method == "POST":
        openid = request.POST.get("open_id")
        user = User.objects.filter(open_id=openid)
        if user.exists():
            user = user.first()
            # json_t = json.dumps(user,skipkeys=True)
            json_user = {
                "id": user.id,
                "username": user.username,
                "avatar_url": user.avatar_url,
                "nick_name": user.nick_name,
                "gender": user.gender,
                "country": user.country,
                "city": user.city,
                "phone": user.phone,
                "create_time": user.create_time,
                "create_id": user.create_id,
                "update_time": user.update_time,
                "update_id": user.update_id,
            }
            data = {
                "code": 1,
                "msg": "ok",
                "data": json.dumps(json_user, default=DateEncoder),
            }
            result = {
                "code": 200,
                "msg": "ok",
                "data": data,
            }

            return HttpResponse(json.dumps(result, default=DateEncoder))
        else:
            # 添加用户到数据库
            data = {
                "code": 1,
                "msg": "查询失败！",
                "data": "",
            }
            result = {
                "code": 200,
                "msg": "error",
                "data": data
            }
            return HttpResponse(json.dumps(result))


def DateEncoder(obj):
    if isinstance(obj, (datetime.datetime, datetime.date)):
        return obj.strftime('%Y-%m-%d')
